package com.yanx.system.base.infra.mapper;

import com.yanx.system.base.domain.entity.SysUser;
import com.yanx.system.base.domain.entity.rel.SysUserPost;
import com.yanx.system.base.domain.entity.rel.SysUserRole;
import com.yanx.system.base.model.dto.SysUserDto;
import org.mapstruct.*;
import org.mapstruct.factory.Mappers;

/**
 * 用户 实体转换类
 *
 * @author: gotanks
 * @create: 2023-2-6
 */
@Mapper(componentModel = "spring", unmappedTargetPolicy = ReportingPolicy.IGNORE,
        nullValuePropertyMappingStrategy = NullValuePropertyMappingStrategy.IGNORE)
public interface SysUserMapper {

    SysUserMapper INSTANCE = Mappers.getMapper(SysUserMapper.class);

    @Mapping(target = "userPosts", source = "postIds")
    @Mapping(target = "userRoles", source = "roleIds")
    SysUser toSysUser(SysUserDto dto);

    @Mapping(target = "userPosts", source = "postIds")
    @Mapping(target = "userRoles", source = "roleIds")
    SysUser toSysUser(SysUserDto dto, @MappingTarget SysUser entity);

    static SysUserPost toSysUserPost(Long postId) {
        SysUserPost sysUserPost = new SysUserPost();
        sysUserPost.setPostId(postId);
        return sysUserPost;
    }

    static SysUserRole toSysUserRole(Long roleId) {
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setRoleId(roleId);
        return sysUserRole;
    }

    @AfterMapping
    static void afterToSysUser(SysUserDto dto, @MappingTarget SysUser entity) {
        Long userId = dto.getId();
        if (entity.getUserPosts() != null) {
            entity.getUserPosts().forEach(t -> t.setUserId(userId));
        }
        if (entity.getUserRoles() != null) {
            entity.getUserRoles().forEach(t -> t.setUserId(userId));
        }
    }
}
